//package cn.xie.blog.servergateway.config;
//
//import cn.xie.blog.servergateway.constants.SecurityConstant;
//import cn.xie.blog.servergateway.filler.CheckTokenFilter;
//import cn.xie.blog.servergateway.filler.CustomUsernamePasswordAuthenticationFilter;
//import cn.xie.blog.servergateway.handler.*;
//import cn.xie.blog.servergateway.security.SecurityConfigManager;
//import cn.xie.blog.servergateway.service.UserDetailsServiceImpl;
//import cn.xie.blog.servergateway.util.PermitAllUrlScanner;
//import jakarta.annotation.Resource;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration;
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.context.annotation.DependsOn;
//import org.springframework.context.annotation.Import;
//import org.springframework.core.annotation.Order;
//import org.springframework.security.authentication.AuthenticationManager;
//import org.springframework.security.authentication.AuthenticationProvider;
//import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
//import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
//import org.springframework.security.config.annotation.web.builders.HttpSecurity;
//import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
//import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer;
//import org.springframework.security.config.http.SessionCreationPolicy;
//import org.springframework.security.config.web.server.ServerHttpSecurity;
//import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
//import org.springframework.security.crypto.password.PasswordEncoder;
//import org.springframework.security.web.SecurityFilterChain;
//import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
//import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
//import org.springframework.security.web.server.SecurityWebFilterChain;
//import org.springframework.web.servlet.handler.HandlerMappingIntrospector;
//
//import java.util.HashSet;
//import java.util.Set;
///**
// * @description: security 配置
// * @author: xiaoxie
// * @date: 2025/4/30 上午11:12
// **/
//@Configuration
//@EnableWebSecurity
//public class SecurityConfig{
//    private static final Logger log = LoggerFactory.getLogger(SecurityConfig.class);
//    @Resource
//    private LogOutHandler logOutHandler;
//
//    @Resource
//    private CheckTokenFilter checkTokenFilter;
//
//    @Resource
//    private LoginFiledHandler loginFiledHandler;
//
//    @Resource
//    private LoginSuccessHandler loginSuccessHandler;
//
//    @Resource
//    private LoginAccessDefineHandler loginAccessDefineHandler;
//
//    @Resource
//    private LoginAuthenticationHandler loginAuthenticationHandler;
//
//    @Resource
//    private UserDetailsServiceImpl userDetailsService;
//
//    @Resource
//    private SecurityConfigManager securityConfigManager;
//    /**
//     * 密码处理器
//     * @return
//     */
//    @Bean
//    public PasswordEncoder passwordEncoder() {
//        return new BCryptPasswordEncoder();
//    }
//
//    /**
//     * 获取AuthenticationManager（认证管理器），登录时认证使用
//     */
//    @Bean(name = "authenticationManager")
//    public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception {
//        return config.getAuthenticationManager();
//    }
//
//    @Bean(name = "mvcHandlerMappingIntrospector")
//    public HandlerMappingIntrospector handlerMappingIntrospector() {
//        return new HandlerMappingIntrospector();
//    }
//    /**
//     * AuthenticationProvider是认证逻辑的提供者
//     *
//     * @return
//     */
//    @Bean
//    public AuthenticationProvider authenticationProvider() {
//        DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
//        daoAuthenticationProvider.setUserDetailsService(userDetailsService);
//        daoAuthenticationProvider.setPasswordEncoder(passwordEncoder());
//        return daoAuthenticationProvider;
//    }
//
//    @Bean
//    @Order(2)
//    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
//        // 获取动态白名单
//        Set<String> dynamicPermitAllUrls = PermitAllUrlScanner.scanPermitAllUrls(SecurityConstant.SCAN_PERMIT_ALL_URLS);
//        // 获取固定白名单
//        Set<String> staticPermitAllUrls = securityConfigManager.getWhiteUrl();
//        // 合并白名单
//        Set<String> allPermitAllUrls = new HashSet<>(staticPermitAllUrls);
//        allPermitAllUrls.addAll(dynamicPermitAllUrls);
//        // 将集合转换为字符串数组
//        String[] whiteUrls = allPermitAllUrls.toArray(String[]::new);
//        //security核心配置
//        http    // 使用自己自定义的过滤器 去过滤接口请求
//                .formLogin(conf -> conf.successHandler(loginSuccessHandler)
//                        //添加管理员登录 URL
//                        .loginProcessingUrl("/web/admin/login") // 登录路径
//                        // 添加普通用户登录 URL
////                        .loginProcessingUrl(SecurityConstant.USER_LOGIN_URL)
//                        .failureHandler(loginFiledHandler)
//                        .usernameParameter("username")
//                        .passwordParameter("password")
//                )
//                .logout(conf ->
//                        conf.logoutUrl(SecurityConstant.LOGOUT_ADMIN_URL)
//                                .logoutUrl(SecurityConstant.LOGOUT_USER_URL)// 自定义登出 URL
//                                .logoutSuccessHandler(logOutHandler) // 自定义登出成功处理器
//                )
//                .addFilterBefore(checkTokenFilter, UsernamePasswordAuthenticationFilter.class)
//                //禁用cors
//                .cors(AbstractHttpConfigurer::disable)
//                //禁用csrf
//                .csrf(AbstractHttpConfigurer::disable)
//                // 配置了会话管理策略为 STATELESS（无状态）。在无状态的会话管理策略下，应用程序不会创建或使用 HTTP 会话，每个请求都是独立的，服务器不会在请求之间保留任何状态信息。
//                .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
//                .authorizeHttpRequests((authorize) ->
//                        authorize.requestMatchers(whiteUrls).permitAll()
//                                .anyRequest().authenticated())
//                //自定义处理器
//                .exceptionHandling(configure ->
//                        configure.authenticationEntryPoint(loginAuthenticationHandler)//未登录处理器
//                                .accessDeniedHandler(loginAccessDefineHandler)//无权限处理器
//                )
//                .headers((header) -> header.frameOptions(HeadersConfigurer.FrameOptionsConfig::sameOrigin));
//        return http.build();
//    }
//    @Bean
//    @DependsOn("authenticationManager")
//    public CustomUsernamePasswordAuthenticationFilter customUsernamePasswordAuthenticationFilter(AuthenticationManager authenticationManager) {
//        return new CustomUsernamePasswordAuthenticationFilter(authenticationManager);
//    }
//
//    @Bean
//    @Order(3)
//    public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
//        http
//                .csrf(csrf -> csrf.disable());
//        return http.build();
//    }
//}